﻿namespace MapleRock.P2PEmulator.Test.Experiments
{
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Globalization;
  using System.IO;
  using System.Linq;
  using System.Text;

  using Core;
  using Core.Events;

  using NUnit.Framework;

  [TestFixture]
  public sealed class GenerateNetworkExperiment
  {
    [TestCase]
    public void GenerateNetwork()
    {
      const int PeersCount = 100000;

      var network = Utils.CreateNetwork(20, 300, 300, 16, 1, 7, PeersCount, PeerBehaviour.DoesNothing);

      const string OutputFilePath = @"d:\out\experiments\generate_network.tsv";

      var path = Path.GetDirectoryName(OutputFilePath);
      Directory.CreateDirectory(path);
      File.Delete(OutputFilePath);

      foreach (var city in network.State.Cities.Values)
      {
        var line = string.Format(
          CultureInfo.InvariantCulture, 
          "{0} {1} {2} {3} {4}\n", 
          city.Id,
          city.Latitude, 
          city.Longitude, 
          city.Radius,
          city.Size);

        File.AppendAllText(
          OutputFilePath, 
          line);
      }

      foreach (var peer in network.State.Peers.Values)
      {
        File.AppendAllText(OutputFilePath, GenerateNetworkExperiment.FormatPeerMeta(peer) + "\n");
        File.AppendAllText(OutputFilePath, GenerateNetworkExperiment.FormatPeerIspCoordinates(peer) + "\n");
        File.AppendAllText(OutputFilePath, GenerateNetworkExperiment.FormatPeerConnection(peer) + "\n");
      }
    }

    private static string FormatPeerIspCoordinates(Peer p)
    {
      var line = string.Format("{0} ", p.AbsolutePosition.Length);
      foreach (var c in p.AbsolutePosition)
      {
        line += string.Format("{0} ", c);
      }

      return line;
    }

    private static string FormatPeerConnection(Peer p)
    {
      var line = string.Format("{0} ", p.ConnectionTable.Count);
      foreach (var r in p.ConnectionTable)
      {
        line += string.Format("{0} ", r.PeerId);
      }

      return line;
    }

    private static string FormatPeerMeta(Peer p)
    {
      return string.Format("{0} {1} {2}", p.Id, p.Address, p.CityId);
    }
  }
}
